import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import JSONBIG from 'json-bigint'
// 默认配置  转换响应数据
const CLIENT_ID = 'mars';
const CLIENT_SECRET = 'mars_secret';
import { Base64 } from 'js-base64';
import router from '@/router';

const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000, // request timeout
  transformResponse: [
    function(data) {
      try {
        // 如果转换成功则返回转换的数据结果
        return JSON.parse(JSON.stringify(JSONBIG.parse(data)));
      } catch (err) {
        // 如果转换失败，则包装为统一数据格式并返回
        return data;
      }
    }
  ]
})
export const clearInfo = () => {
  window.localStorage.removeItem('token');
  window.localStorage.removeItem('user_info');
  store.commit('user/setUserToken', {
    ip: '',
    expire: '',
    jti: '',
    accessToken: '',
    refreshToken: ''
  });
  store.commit('user/setMenuInfo', []);
  store.commit('user/setUserInfo', {
    id: 1,
    adminType: 0,
    account: '',
    name: '',
    nickName: '',
    phone: '',
    sex: 1,
    status: 0,
    empInfoRes: {},
    permissions: [],
    menus: []
  });
}
// request interceptor
service.interceptors.request.use(
  config => {
    let token = store.state.user.user_token.accessToken;
    if (config.headers.withoutToken) {
      token = '';
    }
    config.headers = {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization': `Basic ${Base64.encode(`${CLIENT_ID}:${CLIENT_SECRET}`)}`,
      'Mars-Auth': token || '',
      ...config.headers
    };
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    if (response.status === 200) {
      const res = response.data
      if (res.code !== 200) {
        console.log(11111, res);
        // res.msg !== '账号已存在' && Message({
        //   message: res.msg || 'Error',
        //   type: 'error',
        //   duration: 5 * 1000
        // });
        if (res.code === 1010006 || res.code === 1010005) {
          clearInfo();
          router.push('/login');
        }
      }
      return res;
    } else {
      console.log(11111, response);
      return Promise.reject(response.msg);
    }
  },
  error => {
    if (error.response.data.code === 1010006 || error.response.data.code === 1010005) {
      clearInfo();
      router.push('/login')
    } else {
      if (error.response.data.msg) {
        Message({
          message: error.response.data.msg,
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject(error.response.data.msg);
      } else {
        return Promise.reject(error.response.data);
      }
    }
  }
)

export default service
